<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 提示 -->
    <el-card>
      <el-alert
        show-icon=""
        title="注意：只允许第三级分类修改参数"
        type="warning"
      >
      </el-alert>

      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            clearable
            :props="paramsCascader"
            v-model="parentParams"
            :options="paramsList"
            @change="handleChangeParams"
            emitPath="false"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="only">
          <el-button
            :disabled="istrue"
            type="primary"
            size="mini"
            @click="addParams"
            >添加参数</el-button
          >
          <!-- 动态数据表格 -->

          <el-table :data="onlyData" border stripe>
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="商品名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <!-- 编辑 删除 -->
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top-start"
                  :enterable="false"
                >
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="showDialog(scope.row.attr_id)"
                  ></el-button>
                </el-tooltip>

                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-start"
                  :enterable="false"
                >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteData(scope.row.attr_id)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态数据表格 -->
        <el-tab-pane label="静态属性" name="many">
          <el-button
            :disabled="istrue"
            type="primary"
            size="mini"
            @click="addParams"
            >添加属性</el-button
          >

          <el-table :data="manyData" border stripe>
            <el-table-column type="expand" label="">
              <template slot-scope="scope">
                <!-- 渲染tag标签 -->

                <el-tag
                  closable 
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="handleDlete(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="商品名称"
              prop="attr_name"
            ></el-table-column>

            <el-table-column label="操作">
              <!-- 编辑 删除 -->
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top-start"
                  :enterable="false"
                >
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="showDialog(scope.row.attr_id)"
                  ></el-button>
                </el-tooltip>

                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top-start"
                  :enterable="false"
                >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteData(scope.row.attr_id)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog
      :title="'添加' + textTitle"
      :visible.sync="dialogParams"
      width="40%"
      @close="clearDialog"
    >
      <el-form
        :model="dialogForm"
        :rules="dialogFormRules"
        ref="ruleFormRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="dialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogParams = false">取 消</el-button>
        <el-button type="primary" @click="addParamsData">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性对话框 -->

    <el-dialog
      :title="'修改' + textTitle"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="clearEditDialog"
    >
      <el-form
        :model="editDialogForm"
        :rules="editDialogFormRules"
        ref="editFormRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editDialogForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //props绑定参数
      paramsCascader: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //双向绑定
      parentParams: [],
      //获取到的数据
      paramsList: [],
      //tabs选项卡
      activeName: 'only',
      //动态数据
      onlyData: [],
      //静态数据
      manyData: [],
      // 显示添加属性对话框
      dialogParams: false,
      // 添加属性对话框内容
      dialogForm: {
        attr_name: '',
      },
      //添加规则
      dialogFormRules: {
        attr_name: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      //显示修改对话框
      editDialogVisible: false,
      // 显示规则
      editDialogFormRules: {
        attr_name: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur',
          },
        ],
      },
      editDialogForm: {
        attr_name: '',
        attr_sel: '',
      },
      // 属性ID
      editid: '',
             
    }
  },
  created() {
    this.getParamsList()
  },     
  methods: {
    //获取数据
    async getParamsList() {
      const { data: res } = await this.$http.get('categories')
        
      this.paramsList = res.data
    },
    async handleChangeParams() {
      console.log(this.parentParams)
       if(this.parentParams.length!==3){
        this.parentParams=[]
        this.onlyData=[]
        this.manyData=[]
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.carId}/attributes`,
        { params: { sel: this.activeName } }
      )
      
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible=false
        item.inputValue=''
      })
      console.log(res)
      if (this.activeName == 'only') {
        this.onlyData = res.data
      } else {
        this.manyData = res.data
      }
     


    },
    //显示的tabs选项卡
    handleClick() {
      console.log(this.activeName)
      this.handleChangeParams()
    },
    // 显示添加属性对话框
    addParams() {
      this.dialogParams = true
    },
    clearDialog() {
      this.$refs.ruleFormRules.resetFields()
    },
    clearEditDialog() {
      this.$refs.editFormRules.resetFields()
    },
    //添加属性
    addParamsData() {
      this.$refs.ruleFormRules.validate(async (val) => {
        if (!val) {
          return
        }

        const { data: res } = await this.$http.post(
          `categories/${this.carId}/attributes`,
          {
            attr_name: this.dialogForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status != 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getParamsList()
        this.handleChangeParams()
        this.dialogParams = false
      })
    },
    //展示修改对话框
    async showDialog(id) {
      console.log(id)
      this.editid = id
      const { data: res } = await this.$http.get(
        `categories/${this.carId}/attributes/${id}`
      )

      this.editDialogForm = res.data
      this.editDialogVisible = true
    },
    //修改数据
    async editData() {
      const { data: res } = await this.$http.put(
        `categories/${this.carId}/attributes/${this.editid}`,
        {
          attr_name: this.editDialogForm.attr_name,
          attr_sel: this.editDialogForm.attr_sel,
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.getParamsList()
      this.handleChangeParams()
      this.editDialogVisible = false
      return this.$message.success('修改成功')
    },
    // 删除参数
    async deleteData(id) {
      const confirmrsult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果确认删除 confirm
      //取消 cancel

      if (confirmrsult !== 'confirm') return this.$message.info('已经取消删除')

      const { data: res } = await this.$http.delete(
        `categories/${this.carId}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getParamsList()
      this.handleChangeParams()
      this.editDialogVisible = false
      return this.$message.success('删除成功')
    },
    // 添加tag小标签
  async  handleInputConfirm(row){
      // 如果输入为空或者不合法就转换回去
      if(row.inputValue.trim().length==0){
        row.inputValue=''
        row.inputVisible=false
        return
      }
      //如果输入正确就将数据放到数组中
      row.attr_vals.push(row.inputValue.trim())
       row.inputValue=''
        row.inputVisible=false

         await this.$http.put(
        `categories/${this.carId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        }
      )
    },
    //展示添加小标签按钮
    showInput(row){
      row.inputVisible=true
       this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除小标签
   async handleDlete(i,row){
      row.attr_vals.splice(i,1)
        await this.$http.put(
        `categories/${this.carId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
         attr_sel: row.attr_sel,
          attr_vals:row.attr_vals.join(' ')
        }
      )
    }
  },
  computed: {
    istrue() {
      if (this.parentParams.length == 3) {
        return false
      }
      return true
    },
    carId() {
      if (this.parentParams.length == 3) {
        return this.parentParams[2]
      }
      return null
    },
    textTitle() {
      if (this.activeName == 'only') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>
<style>
.el-cascader-menu {
  width: 100%;
  height: 300px;
}
.input-new-tag{
  width: 120px !important;
}
</style>